/**
 * 权限模块
 */
import React from 'react';
import { connect, Redirect,history } from 'umi';
import { Button, Result } from 'antd';
import RenderAuthorized from '@/components/antdPro/Authorized';
import { fromJS, Map, is, List } from 'immutable';
import commonPkg from '@/utils/commonPkg';

const { store } = commonPkg;

@connect(({ user }) => ({
  authority: user.authority,
  userId: user.user.userId,
}))
export default class extends React.Component {
  shouldComponentUpdate(nextProps, nextState) {
    //优化代码
    return (
      !is(fromJS(this.props), fromJS(nextProps)) ||
      !is(fromJS(this.state), fromJS(nextState))
    );
  }

  getNoMatch = () => {
    const { type } = this.props.route;
    if (type == 'login') {
      return <Redirect to={{ pathname: '/user/login' }} />;
    }
    return (
      <Result
        status="403"
        title="403"
        subTitle="对不起，您没有权限访问此页面"
        extra={
          <Button
            type="primary"
            onClick={() => {
              history.push({ pathname: '/home' });
            }}
          >
            Back Home
          </Button>
        }
      />
    );
  };

  render() {
    const Authorized = RenderAuthorized(this.props.authority); //设置路由权限  RenderAuthorized: (currentAuthority: string | () => string) => Authorized
    return (
      <React.Fragment>
        {this.props.userId && (
          <Authorized
            authority={this.props.route.authority}
            noMatch={this.getNoMatch()}
          >
            {this.props.children}
          </Authorized>
        )}
      </React.Fragment>
    );
  }
}
